package com.sleep.satokendemo.server.impl;

import com.sleep.satokendemo.server.RLimitService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author GuoAo
 * @className RLimitServiceImpl
 * @date 2025/7/27
 * @description TODO
 */
@Service
@Slf4j
public class RLimitServiceImpl implements RLimitService {

    @Resource
    private RedissonClient client;

    private RRateLimiter rateLimiter;


    @Override
    public void testLimit() {
        // 尝试等待3秒
        if(rateLimiter.tryAcquire(3L, TimeUnit.SECONDS)){
            log.info("{} 获取令牌成功",Thread.currentThread().getName());
        }

    }

    @PostConstruct
    public void init(){
        RRateLimiter rateLimiter = client.getRateLimiter("test-rate");
        rateLimiter.trySetRate(RateType.OVERALL, 4, 1, RateIntervalUnit.SECONDS);
        this.rateLimiter = rateLimiter;
    }

    @PreDestroy
    public void destroy(){
        log.info("销毁限流器");
        rateLimiter.delete();
    }
}
